#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

from AppKit import NSPasteboard, NSFilenamesPboardType
from PIL import ImageGrab

import helper
from file_save import FileSave


def get_mac_clipboard_file_paths():
    # 获取剪贴板
    pasteboard = NSPasteboard.generalPasteboard()
    # 检查剪贴板是否包含文件路径类型的数据
    if NSFilenamesPboardType in pasteboard.types():
        # 获取文件路径列表
        file_paths = pasteboard.propertyListForType_(NSFilenamesPboardType)
        if file_paths:
            file_path = file_paths[0]
            if os.path.exists(file_path):
                return file_path
            else:
                return ''
        return ''
    else:
        return ''


def main():
    file_path = get_mac_clipboard_file_paths()
    image = None
    if not file_path:
        try:
            img = ImageGrab.grabclipboard()
            if isinstance(img, ImageGrab.Image.Image):
                image = img
        except BaseException as e:
            helper.notify('Error', str(e))
        else:
            if image is None:
                helper.notify('Error', '剪贴板不存在图片！')
    if file_path or image is not None:
        FileSave(image, file_path)
    else:
        helper.notify('Error', '未获取到文件或图片')


if __name__ == '__main__':
    main()
